package part3.c14_template;

import java.util.Arrays;

/**
 * Created by lie on 2018/3/23.
 * 抽取出流程化部分
 *
 */
public class BubbleSorter {

    static int operations;

    public static int sort(int[] arrays){
        operations = 0;
        int length = arrays.length;
        if (length <= 1) {
            return operations;
        }

        for (int last = length-2;last>=0;last--){
            for (int start=0;start<=last;start++){
                compareAndSwap(arrays, start);
            }
        }

        return operations;
    }

    private static void compareAndSwap(int[] arrays, int start) {
        if (arrays[start] > arrays[start+1])
            swap(arrays, start);
        operations++;
    }

    private static void swap(int[] arrays, int left) {
        int temp = arrays[left + 1];
        arrays[left + 1] = arrays[left];
        arrays[left] = temp;
    }


    public static void main(String[] args){
        int[] arrays = {4, 3, 4, 2, 0, 0, 2, 4, 9, 1, -1};
        int sort = sort(arrays);
        System.out.println("operations = " + sort);
        System.out.println(Arrays.toString(arrays));
    }
}
